<template>
  <a-card>
    <div v-show="showSpin">
      <a-spin tip="正在导出..." size="large">
        <div class="spin-content"></div>
      </a-spin>
    </div>
    <a-form ref="ruleForm" :form="form" v-bind="layout">
      <a-row>
        <a-col :md="8" :sm="24">
          <a-form-item style="margin-bottom: 0" label="仓库名称">
            <a-select v-model="form.pkStordoc" allowClear>
              <a-select-option
                v-for="item in WarehouseCodeList"
                :key="item.depotId"
                :value="
                  item.depotNo + '|' + item.depotName + '|' + item.pkStordoc
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :md="8" :sm="24">
          <a-form-item label="单据状态">
            <a-select v-model="form.auditMark">
              <a-select-option
                v-for="(item, index) in danjuzhuangtailist"
                :value="item.value"
                :key="index"
              >
                {{ item.title }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :md="8" :sm="24">
          <a-form-item label="存货名称" style="margin-bottom: 0">
            <a-select
              style="width: 300px; margin-left: 5px"
              v-model="form.inventoryName"
              @search="handleSearch"
              @change="inventoryNameChange"
              showSearch
            >
              <a-select-option
                v-for="val in stockCodeList"
                :key="val.id"
                :value="
                  val.invcode +
                  '|' +
                  val.inventoryName +
                  '|' +
                  val.invspec +
                  '|' +
                  val.unit +
                  '|' +
                  val.pkInvbasdoc
                "
              >
                {{ val.invcode }} {{ val.inventoryName }}{{ val.invspec }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="会计期间">
            <a-range-picker
              format="YYYY-MM"
              v-model="form.accountingPeriodDate"
            /> </a-form-model-item
        ></a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="签字日期">
            <a-range-picker v-model="form.reviewDate" />
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="收发标志">
            <a-select
              style="width: 300px; margin-left: 5px"
              v-model="form.inboundOutboundIdentification_dirtext"
              @change="inboundOutboundIdentificationHandleChange"
              showSearch
            >
              <a-select-option value="1"> 收类型 </a-select-option>
              <a-select-option value="2"> 发类型 </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" :style="{ textAlign: 'right' }">
          <a-button type="primary" @click="onSubmit">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
          <a-button
            style="margin-left: 8px"
            type="primary"
            @click="exportToExcel"
            >导出</a-button
          >
        </a-col>
      </a-row>
    </a-form>
    <br />
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :scroll="{ x: 3000, y: 670 }"
      @change="handleTableChange"
      size="small"
    >
      <span slot="action" slot-scope="text, record">
        <a-button type="primary" ghost @click="xiangqinghandle(record)">
          详情
        </a-button>
      </span>
    </a-table>
  </a-card>
</template>

<script>
// ------- 公共接口 ------- ;
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax();
import moment from "moment";
import { zhanfbuHttp } from "@/services/modules/ZhangBuChaXun/TaiZhang";
const $http = new zhanfbuHttp();
import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao";
const $zidianhttp = new ZiDianBiaoHttp();
import XLSX from "xlsx";
import { sheet2blob } from "@/utils/export.js";
import FileSaver from "file-saver";
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  {
    title: "会计期间",
    dataIndex: "accountingDate",
  },
  {
    title: "签字日期",
    align: "center",
    dataIndex: "reviewDate",
  },
  {
    title: "仓库名称",
    align: "center",
    dataIndex: "storageUnitName",
  },
  {
    title: "凭证字号",
    align: "center",
    dataIndex: "voucherSize",
  },
  {
    title: "单据号",
    align: "center",
    dataIndex: "document",
    width: "8%",
  },
  {
    title: "批次号",
    align: "center",
    dataIndex: "batchNumber",
  },
  {
    title: "入库单位",
    align: "center",
    dataIndex: "ruunit",
  },
  {
    title: "入库单价",
    align: "center",
    dataIndex: "ruunitPrice",
  },
  {
    title: "入库数量",
    align: "center",
    dataIndex: "ruquantity",
  },
  {
    title: "入库金额",
    align: "center",
    dataIndex: "rumoney",
  },

  {
    title: "出库单位",
    align: "center",
    dataIndex: "chuunit",
  },
  {
    title: "出库单价",
    align: "center",
    dataIndex: "chuunitPrice",
  },
  {
    title: "出库数量",
    align: "center",
    dataIndex: "chuquantity",
  },
  {
    title: "出库金额",
    align: "center",
    dataIndex: "chumoney",
  },
  {
    title: "期初单价",
    align: "center",
    dataIndex: "startUnitPrice",
  },
  {
    title: "期初数量",
    align: "center",
    dataIndex: "startBalance",
  },
  {
    title: "期初金额", // 没有这个
    align: "center",
    dataIndex: "qichujine",
  },
  {
    title: "期末单价", // 没有
    align: "center",
    dataIndex: "qimodanjia",
  },
  {
    title: "期末数量",
    align: "center",
    dataIndex: "finalQuantity",
  },
  {
    title: "期末金额",
    align: "center",
    dataIndex: "finalMoney",
  },
];
export default {
  data() {
    return {
      pagination: {
        current: 1,
        total: 0,
        pageSize: 10, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      columns,
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
      canglubianma_list: [], //仓库编码，
      cunhuofenleilist: [], //存货分类
      cunhuobianmaist: [], //存货编码
      stockCodeList: [], //存货名称
      danjuzhuangtailist: [], //单据状态
      WarehouseCodeList: [], //所属单位
      form: {
        auditMark: "",
        accountingPeriodDate: [],
        invcode: "",
        inventoryName: "",
        pkStordoc: "",
        reviewDate: [],
        inboundOutboundIdentification: "",
        inboundOutboundIdentification_dirtext: "",
      },
      dataSource: [],
      queryPathChache: "",
      showSpin: false, //打印加载中
    };
  },
  mounted() {
    this.gettaizhanglist(); //获取台账列表
    this.getApplyStorage(); //获取仓库列表
    // this.VariousInventoryInformation(); //获取存货表单
    this.getAuditMarkAndDocumentStatus(); //获取单据状态
  },
  methods: {
    inboundOutboundIdentificationHandleChange(value, options) {
      console.log(options);
      this.form.inboundOutboundIdentification = value;
      this.form.inboundOutboundIdentification_dirtext =
        options.componentOptions.children[0].text;
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.gettaizhanglist();
    },

    handleSearch(value) {
      //模糊查询
      this.stockCodeList = [];
      console.log("value", value);
      let query = "?name=" + value;
      console.log("query", query);
      if (value == "" || value == null) {
        this.stockCodeList = [];
      } else {
        comHttp.getgetSearchInventoryInformationFile(query).then((res) => {
          console.log("结果为", res);
          // this.goodsList = res.result;
          for (let i = 0; i < res.result.length; i++) {
            if (
              res.result[i].specificationsModel == "null" ||
              res.result[i].specificationsModel == null
            ) {
              res.result[i].specificationsModel = "";
            }
            if (res.result[i].unit == "null" || res.result[i].unit == null) {
              res.result[i].unit = "";
            }
            let data = {
              key: i,
              inventoryId: res.result[i].id, // 存货 id
              invcode: res.result[i].invcode, //存货编码
              inventoryName: res.result[i].invname, //存货名称
              invspec: res.result[i].invspec, //规格型号
              unit: res.result[i].unit, //单位
              pkInvbasdoc: res.result[i].pkInvbasdoc,
            };
            this.stockCodeList.push(data);
          }
        });
      }
    },
    // 搜索栏选择存货编码编码的change触发函数
    inventoryNameChange(value, option) {
      console.log(value, option);
      this.form.id = option.key;
      // console.log(value , option);

      // const newValue = value.split("|");
      // console.log("搜索栏选择了存货编码", newValue);
      this.form.invcode = value.split("|")[4]; // 存货名称主键
      // this.form.inventoryName = newValue[1];
      // this.form.inventoryInformationId = newValue[2];
    },
    reset() {
      this.form = {
        auditMark: "",
        accountingPeriodDate: [],
        invcode: "",
        inventoryName: "",
        pkStordoc: "",
        reviewDate: [],
        inboundOutboundIdentification: "",
        inboundOutboundIdentification_dirtext: "",
      };
      this.queryPathChache = "";
      this.gettaizhanglist();
    },
    onSubmit() {
      let form = this.form;
      let queryPathChache = "";
      console.log("查询条件：：：");
      console.log(form);
      // 仓库名称
      if (form.pkStordoc) {
        queryPathChache += `&pkStordoc=${form.pkStordoc.split("|")[2]}`;
      }
      // 单据状态
      if (form.auditMark) {
        if (form.auditMark !== "3") {
          queryPathChache += `&auditMark=${form.auditMark}`;
        }
      }
      // 存货名称
      if (form.inventoryName) {
        queryPathChache += `&pkInvbasdoc=${form.inventoryName.split("|")[4]}`;
      }
      if (!form.inventoryName) {
        this.$message.error("选择存货");
        return;
      }

      // 会计期间
      if (form.accountingPeriodDate.length > 0) {
        queryPathChache += `&accountingPeriodBegin=${moment(
          form.accountingPeriodDate[0]
        ).format("YYYY-MM")}`;
        queryPathChache += `&accountingPeriodEnd=${moment(
          form.accountingPeriodDate[1]
        ).format("YYYY-MM")}`;
      }

      // 签字日期
      if (form.reviewDate.length > 0) {
        queryPathChache += `&beginDate=${moment(form.reviewDate[0]).format(
          "YYYY-MM-DD"
        )}`;
        queryPathChache += `&endDate=${moment(form.reviewDate[1]).format(
          "YYYY-MM-DD"
        )}`;
      }
      // 收发标志
      if (form.inboundOutboundIdentification) {
        queryPathChache += `&inboundOutboundIdentification=${form.inboundOutboundIdentification}`;
      }

      console.log("查询调价：：：：：；");
      console.log(queryPathChache);
      this.queryPathChache = queryPathChache;
      this.gettaizhanglist(); //获取台账列表

      // let query =
      //   "?storageUnit=" +
      //   form.pkStordoc +
      //   "&inventoryName=" +
      //   form.inventoryName +
      //   "&BusinessDateBeginning=" +
      //   this.BusinessDateBeginning() +
      //   "&BusinessDateEnding=" +
      //   this.BusinessDateEnding() +
      //   "&AccountingDateBeginning=" +
      //   this.AccountingDateBeginning() +
      //   "&AccountingDateEnding=" +
      //   this.AccountingDateEnding();

      // if (form.auditMark != 3) {
      //   query += "&auditMark=" + form.auditMark;
      // }

      // $http.taizhangchaxun(query).then((res) => {
      //   if (res.success) {
      //     this.$message.success("查询成功");
      //     this.data = res.result;
      //     for (let i = 0; i < this.data.length; i++) {
      //       if (this.data[i].inOutIdentification == 1) {
      //         (this.data[i].ruquantity = this.data[i].quantity),
      //           (this.data[i].ruunit = this.data[i].unit);
      //         (this.data[i].ruunitPrice = this.data[i].unitPrice),
      //           (this.data[i].rumoney = this.data[i].money);
      //       }
      //       if (this.data[i].inOutIdentification == 2) {
      //         (this.data[i].chuquantity = this.data[i].quantity),
      //           (this.data[i].chuunit = this.data[i].unit);
      //         (this.data[i].chuunitPrice = this.data[i].unitPrice),
      //           (this.data[i].chumoney = this.data[i].money);
      //       }
      //       if (this.data[i].auditMark === 1) {
      //         this.data[i].auditMark = "已审核";
      //       }
      //       if (this.data[i].auditMark === 2) {
      //         this.data[i].auditMark = "未审核";
      //       }
      //     }
      //     return;
      //   } else {
      //     this.$message.error("查询失败");
      //   }
      // });
    },
    exportToExcel() {
      this.showSpin = true; //打印加载中
      // if (this.searchForm.sort === undefined) {
      //   this.searchForm.sort = "";
      // }
      // if (this.searchForm.inventoryName === undefined) {
      //   this.searchForm.inventoryName = "";
      // }
      $http
        .gettaizhanglist(
          "?pageNo=1&pageSize=" + this.maxSize + this.queryPathChache
        )
        .then((res) => {
          console.log("导入的数据", res.result.records);
          let array = res.result.records;
          this.exportBasic(array);
        });
    },
    //  接收数组，进行导出
    exportBasic(Array) {
      console.log("要导出的数据为:::::", Array);
      //  规整要导出的数据:::::
      let array = [];
      for (let i = 0; i < Array.length; i++) {
        let data = {
          序号: i + 1,
          会计期间: Array[i].accountingPeriodDate,
          签字日期: Array[i].businessDate,
          仓库名称: Array[i].storname,
          单据号: Array[i].document,
          入库单位: Array[i].measname,
          入库单价: Array[i].inUnitPrice,
          入库数量: Array[i].inQuantity,
          入库金额: Array[i].inMoney,
          出库单位: Array[i].measname,
          出库单价: Array[i].outUnitPrice,
          出库数量: Array[i].outQuantity,
          出库金额: Array[i].outMoney,
          凭证字号: null,
          批次号: null,
          期初单价: null,
          期初数量: Array[i].beginningQuantity,
          期初金额: null,
          期末单价: null,
          期末数量: null,
        };
        array.push(data);
      }
      // 生成 sheet 表格 数据
      let sheet = XLSX.utils.json_to_sheet(array, {
        // 对导出内容进行相应的排序,手动排序。
        header: [
          "序号",
          "会计期间",
          "签字日期",
          "仓库名称",
          "单据号",
          "入库单位",
          "入库单价",
          "入库数量",
          "入库金额",
          "出库单位",
          "出库单价",
          "出库数量",
          "出库金额",
          "凭证字号",
          "批次号",
          "期初单价",
          "期初数量",
          "期初金额",
          "期末单价",
          "期末数量",
        ],
      });
      // 生成导出表格
      let blob = sheet2blob(sheet);
      try {
        FileSaver.saveAs(
          new Blob([blob], {
            type: "application/octet-stream",
          }),
          "台账.xlsx" // 导出文件夹名称
        );
      } catch (e) {
        console.log(e);
      }
      this.showSpin = false; //导出中
    },
    BusinessDateBeginning() {
      if (this.form.reviewDate[0]) {
        return `${moment(this.form.reviewDate[0]).format("YYYY-MM-DD")}`;
      } else {
        return "";
      }
    },
    BusinessDateEnding() {
      if (this.form.reviewDate[1]) {
        return `${moment(this.form.reviewDate[1]).format("YYYY-MM-DD")}`;
      } else {
        return "";
      }
    },
    AccountingDateBeginning() {
      if (this.form.accountingPeriodDate[0]) {
        return `${moment(this.form.accountingPeriodDate[0]).format("YYYY-MM")}`;
      } else {
        return "";
      }
    },
    AccountingDateEnding() {
      if (this.form.accountingPeriodDate[1]) {
        return `${moment(this.form.accountingPeriodDate[1]).format("YYYY-MM")}`;
      } else {
        return "";
      }
    },
    //弹出日历和关闭日历的回调
    /* onChange(date, dateString) {
      console.log(date, dateString);
    }, */
    //单据状态
    getAuditMarkAndDocumentStatus() {
      $zidianhttp.getAuditMarkAndDocumentStatus().then((res) => {
        this.danjuzhuangtailist = res.result;
        console.log(this.danjuzhuangtailist);
      });
    },

    getApplyStorage() {
      this.WarehouseCodeList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            id: res.result[i].pkStordoc,
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            pkStordoc: res.result[i].pkStordoc,
          };
          this.WarehouseCodeList.push(data);
        }
        console.log("返回仓库编码、仓库名称", this.WarehouseCodeList);
      });
    },

    // gettaizhanglist() {
    //   //台账列表
    //   $http.gettaizhanglist().then((res) => {
    //     let data = res.result;

    //     // console.table(data);

    //     for (let i = 0; i < data.length; i++) {
    //       if (data[i].inOutIdentification == 1) {
    //         data[i].ruquantity = data[i].quantity;
    //         data[i].ruunit = data[i].unit;
    //         data[i].ruunitPrice = data[i].unitPrice;
    //         data[i].rumoney = data[i].money;
    //       } else if (data[i].inOutIdentification == 2) {
    //         data[i].chuquantity = data[i].quantity;
    //         data[i].chuunit = data[i].unit;
    //         data[i].chuunitPrice = data[i].unitPrice;
    //         data[i].chumoney = data[i].money;
    //       }

    //       if (data[i].auditMark === 1) {
    //         data[i].auditMark = "已审核";
    //       } else if (data[i].auditMark === 2) {
    //         data[i].auditMark = "未审核";
    //       }
    //     }

    //     this.data = data;

    //     console.log(res);

    //     console.log(this.data);
    //   });
    // },
    gettaizhanglist() {
      const { current } = this.pagination; // 分页第一步：拿到要跳转的页数
      let query = `?pageNo=${current}${this.queryPathChache}`;
      $http.gettaizhanglist(query).then((res) => {
        console.log("台账", res);
        // 分页第二步：将服务七返回的分页数据存储到页面上
        this.pagination.current = res.result.current;
        this.pagination.total = res.result.total;
        this.pagination.pageSize = res.result.size;
        this.maxSize = res.result.total;
        // this.dataSource = ;
        let dataSource = [];
        const data = res.result.records;
        for (let i = 0; i < data.length; i++) {
          let item = data[i];
          let Data = {
            key: i + (current - 1) * res.result.size + 1, // 分页3：修改数据序号
            accountingDate: item.accountingPeriodDate, // 会计期间
            reviewDate: item.businessDate, // 签字日期
            storageUnitName: item.storname, // 仓库名称
            // 存货名称
            document: item.document, // 单据号
            ruunit: item.measname, // 入库单位
            ruunitPrice: item.inUnitPrice, // 入库单价
            ruquantity: item.inQuantity, // 入库数量
            rumoney: item.inMoney, // 入库金额
            chuunit: item.measname, // 出库单位
            chuunitPrice: item.outUnitPrice, // 出库单价
            chuquantity: item.outQuantity, // 出库数量
            chumoney: item.outMoney, // 出库金额
            batchNumber: null, // 批次号
            voucherSize: null, // 凭证字号
            startUnitPrice: null, // 期初单价
            startBalance: item.beginningQuantity, // 期初数量
            qichujine: null, // 期初金额
            qimodanjia: null, // 期末单价
            finalMoney: null, // 期末数量
          };

          dataSource.push(Data);
        }
        this.dataSource = dataSource;
        if (this.dataSource == undefined || this.dataSource.length <= 0) {
          this.$message.warning("暂无符合查询条件的数据");
        }
      });
    },
  },
};
</script>

<style></style>